package com.wsmlby.vmd.visualization;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

public abstract class VMDDataReader {
	protected File mFile;
	protected InputStream mInputStream;
	protected InputStreamReader mStreamReader;
	protected BufferedReader mBufferedReader;
	class AtomData
	{
		int Type;
		String id;
		Vector3 Position;
		
	}
	class TimeByteData
	{
		byte[] data;
		int TimeStep,NumberOfAtoms;
		static final public int ELEMSIZE=16;
		public TimeByteData(TimeStep t) {
			data=new byte[t.Atoms.size()*ELEMSIZE];
			TimeStep=t.TimeStep;
			NumberOfAtoms=t.NumberOfAtoms;
			int n=t.Atoms.size();
			for(int i=0;i<n;i++)
			{
				AtomData a=t.Atoms.get(i);
				byte []bs=Codec.int2byte(a.Type);
				System.arraycopy(bs, 0, data, i*ELEMSIZE, bs.length);
				bs=Codec.int2byte(Float.floatToIntBits(a.Position.x));
				System.arraycopy(bs, 0, data, i*ELEMSIZE+4, bs.length);
				bs=Codec.int2byte(Float.floatToIntBits(a.Position.y));
				System.arraycopy(bs, 0, data, i*ELEMSIZE+8, bs.length);
				bs=Codec.int2byte(Float.floatToIntBits(a.Position.z));
				System.arraycopy(bs, 0, data, i*ELEMSIZE+12, bs.length);
				
			}
		}
	}
	class TimeStep
	{
		int TimeStep,NumberOfAtoms;
		
		protected ArrayList<AtomData> Atoms;
		HashMap<String, AtomData> hash;
		public TimeStep()
		{
			Atoms=new ArrayList<VMDDataReader.AtomData>();
			hash=new HashMap<String, VMDDataReader.AtomData>();
		}
		public void AddAtom(AtomData a)
		{
			Atoms.add(a);
			hash.put(a.id, a);
		}
		public TimeByteData ToByteData()
		{
			return new TimeByteData(this);	
		}
	}
	public VMDDataReader(File f) throws FileNotFoundException
	{
		mFile=f;
		mInputStream=new FileInputStream(f);
		mStreamReader=new InputStreamReader(mInputStream);
		mBufferedReader=new BufferedReader(mStreamReader);
		
	}
	public void finalize()
	{
		
		try {
			mInputStream.close();
			mBufferedReader.close();
			mStreamReader.close();
		} catch (IOException e1) {
		}
		try {
			super.finalize();
		} catch (Throwable e) {
			
		}
		
	}
	public abstract boolean isType();
	public abstract TimeStep getNextTimeStep() throws IOException;

}
